<template>
  <Dialog v-model="visible" width="30vw" title="选择功能">
    <el-tree ref="treeRef" :data="data" node-key="value" :default-expanded-keys="value?.value ? [value.value] : undefined" @node-click="onNodeClick" />
    <template #footer>
      <div class="flex justify-center items-center">
        <el-button type="primary" @click="ok">确定</el-button>
        <el-button @click="hide">关闭</el-button>
      </div>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
  import { Dialog } from '@/components/Popup';
  import { ElTree, ElButton } from 'element-plus';
  import { onMounted, ref } from 'vue';

  const props = defineProps<{modelValue?: Record<string, string>, data: any[]}>()
  const emits = defineEmits(['update:modelValue'])
  
  const visible = ref(false)
  const value = ref(props.modelValue)
  const treeRef = ref()

  const onNodeClick = (data, node) => {
    if(!data.value) return

    value.value = data
    const items = data.value.split('.')

    let label = node.data.label
    // for(let i = items.length - 1; i >= 0; i --) {
    //   const item = items[i]
    //   if(!item) break


    // }
    const len = items.length
    if(len === 2) { // .action, micro.action
      value.value.fullLabel = items[0] ? `${node.parent.data.label}->${node.data.label}` : node.data.label
    } else {// .seed.action, micro.seed.action
      value.value.fullLabel = items[0]
          ? `${node.parent.parent.data.label}->${node.parent.data.label}->${node.data.label}`
          : `${node.parent.data.label}->${node.data.label}`
    }
  }
  const ok = () => {
    emits('update:modelValue', value.value)
    hide()
  }

  onMounted(() => treeRef?.value?.setCurrentKey(value.value))

  const show = () => visible.value = true
  const hide = () => visible.value = false
  defineExpose({ show, hide })
</script>